package com.example.demo.service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import com.example.demo.model.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * @author yujie
 * @create 2018-01-12 上午10:49
 **/
@Service
public class TestUserService implements ApplicationContextAware, InitializingBean, DisposableBean {

    @PostConstruct
    private void init() {
        /**
         * 私有方法也可以被调用
         */
        System.out.println(1);
    }

    @PreDestroy
    private void preDestroy() {
        System.out.println("3-1");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        /**
         * 通过实现ApplicationContextAware获得applicationContext
         */
        System.out.println(0);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("3-2");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(2);
        /**
         * 通过实现InitializingBean的afterPropertiesSet 可以在属性加载后处理业务逻辑
         */
    }

    public TestUserService() {
    }


    @Cacheable(value = "user", key = "'getUser:'+#a.get('a')")
    public User getUser(Map<String, String> a) throws Exception {
        User user = new User();
        if (a == null) {
            throw new Exception("什么问题啊");
        }
        user.setA(a.get("a"));
        return user;
    }

    @CacheEvict(value = "user", allEntries = true)
    public void delete() {

    }

    @Cacheable(value = "student", key = "'st'")
    public String st() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "abc";
    }
}
